package com.example.musicaiap.ui.community

import android.util.Log
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults // Import TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color // Import Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.ui.player.PlayerController
import com.example.musicaiap.ui.player.PlayerViewModel
import com.example.musicaiap.ui.player.PlayerContract.PlayerIntent

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommunityScreen(
    viewModel: CommunityViewModel,
    playerViewModel: PlayerViewModel,
    playerController: PlayerController
) {
    val favoriteSongs by viewModel.favoriteSongs.collectAsState(initial = emptyList())
    val isLoading by viewModel.isLoading.collectAsState()

    Scaffold(
        containerColor = Color.Transparent, // Make Scaffold background transparent
        topBar = {
            TopAppBar(
                title = { Text("我的收藏") },
                actions = {
                    IconButton(onClick = { /* TODO: 添加分享功能 */ }) {
                        Icon(Icons.Default.Favorite, contentDescription = "分享")
                    }
                },
                // Make TopAppBar transparent as well to see global background
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.Transparent,
                    titleContentColor = MaterialTheme.colorScheme.onSurface, // Adjust as needed
                    actionIconContentColor = MaterialTheme.colorScheme.onSurfaceVariant // Adjust as needed
                )
            )
        }
    ) { paddingValues ->
        // Apply padding to the content Box, not the Scaffold itself if containerColor is transparent
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues) // Apply padding here
        ) {
            if (isLoading) {
                CircularProgressIndicator(
                    modifier = Modifier.align(Alignment.Center)
                )
            } else if (favoriteSongs.isEmpty()) {
                Text(
                    text = "暂无收藏歌曲",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.align(Alignment.Center)
                )
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    modifier = Modifier.fillMaxSize()
                ) {
                    items(favoriteSongs) { song ->
                        FavoriteSongItem(
                            song = song,
                            onPlayClick = {
                                // 获取歌曲在列表中的索引
                                val songIndex = favoriteSongs.indexOfFirst { it.id == song.id }
                                if (songIndex != -1) {
                                    // 播放整个收藏歌曲列表，从点击的歌曲开始
                                    Log.d("CommunityScreen", "播放收藏列表，从索引 $songIndex 开始，列表大小: ${favoriteSongs.size}")
                                    playerController.play(favoriteSongs, songIndex, "FAVORITES")
                                    // 同时更新PlayerViewModel的状态
                                    playerViewModel.processIntent(PlayerIntent.PlaySong(song))
                                } else {
                                    // 如果找不到索引（理论上不应该发生），则单独播放该歌曲
                                    Log.d("CommunityScreen", "未找到歌曲索引，单独播放: ${song.title}")
                                    playerController.play(song)
                                    playerViewModel.processIntent(PlayerIntent.PlaySong(song))
                                }
                            },
                            onFavoriteClick = {
                                viewModel.toggleFavorite(song.id)
                            }
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun FavoriteSongItem(
    song: Song,
    onPlayClick: () -> Unit,
    onFavoriteClick: () -> Unit
) {
    Card(
        onClick = onPlayClick,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        // Consider making Card background slightly transparent or using surface variant
        // colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f))
    ) {
        Column {
            AsyncImage(
                model = ImageRequest.Builder(LocalContext.current)
                    .data(song.coverUrl)
                    .crossfade(true)
                    .build(),
                contentDescription = song.title,
                modifier = Modifier.fillMaxWidth(),
                contentScale = ContentScale.Crop
            )
            Text(
                text = song.title,
                style = MaterialTheme.typography.titleMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
            )
            Text(
                text = song.artist,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
            )
        }
    }
}
